<template>
<div class="dashboard-container">
    <div class="app-container">
        <!-- 头部 -->
        <PageTools :show-before="true">
            <template #before>
                <span>共{{ pageParams.total }}条数据</span>
            </template>
            <template #after>
                <el-button type="primary" size="mini" @click="$router.push('/import?type=addEmp')">导入</el-button>
                <el-button type="primary" size="mini" @click="ToExcel">导出</el-button>
                <el-button type="primary" size="mini" @click="isShowDialog = true">新增员工</el-button>
            </template>
        </PageTools>
        <!-- 主体 -->
        <el-card v-loading="isLoading" class="employees_main">
            <el-table border :data="employeesList">
                <el-table-column
                    width="50px"
                    :fit="false"
                    header-align="left"
                    align="center"
                    type="index"
                    fixed
                    sortable
                    prop="index"
                    :label="$t('table.id')"
                />
                <el-table-column
                    header-align="left"
                    align="center"
                    sortable
                    prop="staffPhoto"
                    :label="$t('table.avatar')"
                    class="staffPhoto"
                >
                    <template slot-scope="{row}">
                        <img
                            v-imgErr="require('@/assets/common/bigUserHeader.png')"
                            style="border-radius: 50%; width: 5.5vw; height: 5.5vw; object-fit: cover;"
                            :src="row.staffPhoto"
                            @click="showQrCode(row.staffPhoto,row.id)"
                        />
                    </template>
                </el-table-column>
                <el-table-column sortable prop="username" :label="$t('table.name')" />
                <el-table-column sortable prop="workNumber" :label="$t('table.jobNumber')" />
                <el-table-column
                    sortable
                    prop="formOfEmployment"
                    :label="$t('table.hireForm')"
                    :formatter="EmployeeMatter"
                />
                <el-table-column sortable prop="departmentName" :label="$t('table.department')" />
                <el-table-column sortable :label="$t('table.entryTime')">
                    <template slot-scope="{row}">
                        {{ row.correctionTime | formatDate }}
                    </template>
                </el-table-column>
                <el-table-column sortable label="账户状态">
                    <template slot-scope="{row}">
                        <el-switch
                            :value="row.enableState === 1"
                            active-color="##1e8cfc"
                            inactive-color="#8a8a8a"
                        >
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column
                    fixed="right"
                    prop=""
                    label="操作"
                    width="280"
                >
                    <template slot-scope="{row}">
                        <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看
                        </el-button>
                        <el-button type="text" size="small">转正</el-button>
                        <el-button type="text" size="small">调岗</el-button>
                        <el-button type="text" size="small">离职</el-button>
                        <el-button type="text" size="small" @click="setRole(row)">角色</el-button>
                        <el-button type="text" size="small" @click="handleDel(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                layout="prev, pager, next"
                :page-size="pageParams.size"
                :current-page="pageParams.page"
                :total="pageParams.total"
                el-card
                @current-change="changePage"
            >
            </el-pagination>
        </el-card>
        <addEmployee :is-show-dialog.sync="isShowDialog"></addEmployee>
        <!-- 弹窗 -->
        <el-dialog
            title="二维码"
            :visible.sync="showCodeDialog"
            @close="imgUrl=''"
        >
            <el-row type="flex" justify="center">
                <canvas ref="myCanvas" />
            </el-row>
        </el-dialog>
        <!-- 角色弹窗 -->
        <assignRole ref="AssignRole" :is-assign-role.sync="isAssignRole" :user="NowRole"></assignRole>
    </div>
</div>
</template>

<script>
import {
	formatDate
} from '@/utils/index.js'
import addEmployee from './components/addEmployees.vue'
import assignRole from './components/assign-role.vue'
import {
	getEmployeeList,
	delEmployee
} from '@/api/employees.js'
import employeeNum from '@/api/constant/employees.js'
import QrCode from 'qrcode'
export default {
	components: {
		addEmployee,
		assignRole
	},
	data() {
		return {
			/* 被点击角色 */
			NowRole: {},
			/* 角色弹窗 */
			isAssignRole: false,
			isLoading: false,
			isShowDialog: false,
			/* 二维码弹窗 */
			showCodeDialog: false,
			/* 页面数据 */
			pageParams: {
				page: 1,
				size: 10,
				total: 0
			},
			/* 员工数据列表 */
			employeesList: []
		}
	},
	created() {
		this.getEmployeeList(this.pageParams)
	},
	methods: {
		async getEmployeeList(params) {
			this.isLoading = true
			const {
				rows,
				total
			} = await getEmployeeList(params)
			this.pageParams.total = total
			this.employeesList = rows
			this.isLoading = false
		},
		/* 分页切换 */
		changePage(page) {
			this.pageParams.page = page
			this.getEmployeeList(this.pageParams)
		},
		/* 格式化聘用形式 */
		EmployeeMatter(row, column, cellValue, index) {
			const obj = employeeNum.hireType.find(item => item.id === Number(cellValue))
			return obj ? obj.value : '未知'
		},
		/* 删除员工 */
		handleDel(row) {
			this.$confirm(`确定删除员工${row.username}？`)
				.then(async() => {
					await delEmployee(row.id)
					await this.getEmployeeList(this.pageParams)
					this.$message.success('删除成功！')
				})
				.catch(e => {})
		},
		/* 导出Excel */
		ToExcel() {
			// 表头对应关系
			const dict = {
				'姓名': 'username',
				'手机号': 'mobile',
				'入职日期': 'timeOfEntry',
				'聘用形式': 'formOfEmployment',
				'转正日期': 'correctionTime',
				'工号': 'workNumber',
				'部门': 'departmentName'
			}
			// 按需加载
			import('@/vendor/Export2Excel.js').then(async excel => {
				const Enheaders = Object.values(dict)
				const {
					rows
				} = await getEmployeeList({
					page: 1,
					size: this.pageParams.total
				})
				const res = rows.map(item => {
					return Enheaders.map(key => {
						// 日期统一处理
						if (key === 'timeOfEntry' || key === 'correctionTime') {
							return formatDate(item[key], 'yyyy/MM/dd')
							// 聘用形式统一处理
						} else if (key === 'formOfEmployment') {
							const xx = employeeNum.hireType.find(obj => obj.id === Number(
								item[key]))
							return xx ? xx.value : '未知'
						}
						return item[key]
					})
				})
				console.log(res)
				const multiHeader = [
					['姓名', '主要信息', '', '', '', '', '部门'],
					['', '入职信息', '', '', '']
				]
				const exportHeaders = Object.keys(dict)
				exportHeaders[exportHeaders.indexOf('姓名')] = ''
				exportHeaders[exportHeaders.indexOf('部门')] = ''
				const merges = ['A1:A3', 'G1:G3', 'B1:F1', 'B2:D2']
				excel.export_json_to_excel({
					header: exportHeaders,
					data: res,
					filename: '员工信息表',
					multiHeader,
					merges,
					autoWidth: true,
					bookType: 'xlsx'

				})
			})
		},
		/* 二维码生成方法 */
		showQrCode(url, id) {
			console.log(url)
			// url存在的情况下 才弹出层
			if (url) {
				this.showCodeDialog = true // 数据更新了 但是我的弹层会立刻出现吗 ？页面的渲染是异步的！！！！
				// 有一个方法可以在上一次数据更新完毕，页面渲染完毕之后
				this.$nextTick(() => {
					// 此时可以确认已经有ref对象了
					QrCode.toCanvas(this.$refs.myCanvas, url) // 将地址转化成二维码
					// 如果转化的二维码后面信息 是一个地址的话 就会跳转到该地址 如果不是地址就会显示内容
				})
			} else {
				this.$message.warning('该用户还未上传头像')
			}
		},
		/* 设置角色 */
		async setRole(row) {
			this.NowRole = row
			await this.$refs.AssignRole.getUserDetail(this.NowRole.id)
			this.isAssignRole = true
		}

	}
}
</script>

<style lang="scss" scoped>
	.employees_main {
		margin-top: 30px;

		.el-pagination {
			margin-top: 20px;
			text-align: center;
		}
	}
</style>
